<template>
  <div class="card">
    <headerNav title="购物车" v-if="isType=='detail'"/> 
    <div class="card_title" v-else>购物车</div>
    <!-- <p class="del" @click="compile">{{msg}}</p> -->
    <div v-if="cartInfo">
      <div class="card-goods">
        <div class="promotion-group" :style="{bottom:promotionBottom}">
          <div  v-for="(item,index) in goods"
            :key="index+20" class="card-goods__item"> 
            <van-checkbox 
              v-model="item.checked"
              @change="chooseChange(item)"></van-checkbox>
            <van-cell-group class="additional cart_page">
              <van-card
              :title="item.itemTitle"
              style="background:#fff"
              >
                <template slot="thumb">
                  <img :src="item.narrowPicUrl" />
                </template>
                <template slot="tags">
                  <div class="tags">
                    <p class="price" v-if="item.price!=null&&item.price!=''" >
                      ￥<span>{{item.price}}</span>
                    </p>
                    <div class="quantity">
                      <span @click="subtractNum(item)">-</span>
                      <input type="text" v-model="item.num" disabled>
                      <span @click="addNum(item)">+</span>
                    </div>
                    <!-- <van-stepper :value="item.num" :name="item.itemNo"  min="1" @change="onChangeNum"/> -->
                  </div>    
                </template>
              </van-card>
              <slot />
            </van-cell-group>
          </div>
        </div>
      </div>
      <!-- 结算 -->
      <div class="account">
        <van-submit-bar
          :price="totalPrice"
          :button-text="submitBarText"
          :disabled = "disabled"
          @submit="onSubmit"
          :style="{bottom:accountBottom}"
        >
        <template slot>
          <van-checkbox v-model="isCheckAll" @change="onChangeAllSelect">全选</van-checkbox>
        </template>
        </van-submit-bar>
      </div>
    </div>  
    <div class="cart_null" v-if="!cartInfo">
      <img src="../../assets/images/nocart.png">
      <p>购物车空空如也 ~</p>
      <span @click="stroll">去逛逛</span>
    </div>
    <navigate v-if="isType!='detail'"/>
  </div>
</template>

<script>
import cart from "../../data/sku.js";
export default {
  components: {
  },
  data() {
    return {
      isCheckAll:false,
      checkedGoods: [],
      cartInfo:false,
      total:0,
      goods:[],
      selectedData:[],
      selectedId:[],
      single:false,
      msg:"编辑",
      falg:false,
      delSelectId:[],
      token:"",
      disabled:false,
      isType:this.$route.query.type,
      promotionBottom:null,
      accountBottom:null,
    };
  },
  computed: {
    submitBarText() {
      if(this.falg){
        return '删除'
      }else{
        return '结算'
      }
    },
    totalPrice() {
      let allprice = 0
      this.selectedData.map(item=>{
        allprice = parseFloat(allprice) + (parseInt(item.num) * parseFloat(item.price));  
      })
      return allprice*100;
    },
  },
  methods: {  
    stroll(){
      this.$router.push({name:""})
    },
    onSubmit() { 
      if(!this.falg){
        if(this.token==""){
          this.$toast("请先登录~");
          this.$router.push({ name: "login"});
        }else{
          this.$store.dispatch("setShopping", this.selectedData);
          this.$router.push({ name: "order",query:{Source:1}});
        }
      }else{
        // 删除购物车商品
        let ShoppingCart = localStorage.getItem("ShoppingCart");  
        let jsonstr = JSON.parse(ShoppingCart.substr(1, ShoppingCart.length));  
        let productlist = jsonstr.productlist;   
        // 将选中数据从localStorage中删除
        this.delSelectId.map(item=>{
          productlist.map((listData,index)=>{
            if (listData.itemNo == item) {  
              productlist.splice(index,1)
              jsonstr.totalNumber = parseInt(jsonstr.totalNumber) - parseInt(listData.num);  
              jsonstr.totalAmount = parseFloat(jsonstr.totalAmount) - parseInt(listData.num) * parseFloat(listData.price);  
            }
          })
        })
        // 将数据重新初始化
        localStorage.setItem("ShoppingCart", "'" + JSON.stringify(jsonstr)); 
        this.goods = cart.getproductlist();
        this.cartInfo = cart.existproduct();
        this.delData()
      }
      
    },
    // 一键全选
    _shopTrue () {
      this.goods.map(pro => {
        pro.checked = true
        if(!this.falg){
          cart.changeSelect(pro.itemNo,pro.checked)
          this.addSelsect(pro);
        }
      })
    },
    // 一键全不选
    _shopFalse () {
      this.goods.map(pro => {
        pro.checked = false
        if(!this.falg){
          cart.changeSelect(pro.itemNo,pro.checked)
          this.selectedData = []
          this.selectedId = []
        }
      })
    },
    // 单个商品按钮改变
    chooseChange(item){
      if(item.checked){
        // 选中状态
        this.addSelsect(item)
        this.delSelectId.push(item.itemNo)
      }else{
        // 取消状态
        // 编辑状态--将数据从已选数据中删除
        this.selectedData.map((data,index)=>{
          if(data.itemNo==item.itemNo){
            this.selectedData.splice(index,1)
          }
        })
        var val = this.selectedId.indexOf(item.itemNo)
        this.selectedId.splice(val,1)
         // 删除状态--将数据从已选数据中删除
        var valDel = this.delSelectId.indexOf(item.itemNo)
        this.delSelectId.splice(valDel,1)
      }
      if(!this.falg){
        // 编辑时更新localStorage中的数据
        cart.changeSelect(item.itemNo,item.checked)
      }else{
        // 删除操作--删除按钮是否可点击
        if(this.delSelectId.length>0){
          this.disabled = false;
        }else{
          this.disabled = true;
        }
      }
      this.AllSelect()
    },
    //添加选择的商品
    addSelsect(item){
      // 判断商品是否已存在
      if (this.selectedId.indexOf(item.itemNo) > -1){
        return
      }else{
        item.itemName = item.itemTitle
        item.itemNarrowPic = item.narrowPicUrl
        this.selectedData.push(item)
        this.selectedId.push(item.itemNo)
      }
    },
    // 判断商品是否全部选择
    AllSelect(){
      if(this.selectedId.length == this.goods.length||this.delSelectId.length == this.goods.length){
        this.isCheckAll = true 
        this.single = true
      }else{
        this.single = false
        this.isCheckAll = false
      }
    },
    //全选按钮改变
    onChangeAllSelect(){
      if(this.isCheckAll){
        this._shopTrue()
      }else{
        if(this.single){
          this._shopFalse()
        }
      }
    },
    //数量加
    addNum(item){
      item.num++;
      cart.updateproductnum(item.itemNo,item.num)
    },
    // 数量减
    subtractNum(item){
      if(item.num<=1){
        this.$toast("宝贝不能再少了~")
        return
      }
      item.num--;
      cart.updateproductnum(item.itemNo,item.num)
    },
    // 编辑
    compile(){
      this.falg = !this.falg
      if(this.falg){
        this.msg = "完成"
        this.delData()
      }else{
        this.msg = "编辑"
        this.disabled = false;
        this.delSelectId = [];
        this.analysis()
      }
    },
    // 删除操作更新数据
    delData(){
      this.goods.map(item=>{
        item.checked = false
      })
      this.selectedData = []
      this.disabled = true
    },
    //解析存储的数据
    analysis(){
      this.goods = cart.getproductlist();
      this.goods.map(item=>{
        if(item.checked){
          this.addSelsect(item)
        }
      })
      this.AllSelect()
    },
    getpromotion(){
      if(this.isType=="detail"){
        this.promotionBottom = "0.51rem"
        this.accountBottom = "0"
      }else{
        this.promotionBottom = "1rem"
        this.accountBottom = "0.5rem"
      }
    },
  },
  mounted(){
    this.getpromotion()
    let userInfo = JSON.parse(window.localStorage.getItem("userInfo"));
    if(userInfo!=null && userInfo!=undefined){
      this.token = userInfo.token
    }
    this.cartInfo = cart.existproduct();
    if(this.cartInfo){
      this.analysis()
    } 
  },
};
</script>

<style lang="less">
.card-goods {
  font-size: 12px;
  &__item {
    position: relative;
    .van-checkbox{
      width: 20px;
      height: 20px;
      top: .5rem;
      left: .15rem;
      z-index: 1;
      position: absolute;
    }
    .additional{
      width: 100%;
      padding-left: .3rem;
      box-sizing: border-box;
    }
  }
}
.card_title{
  height: .46rem;
  font-size: .16rem;
  text-align: center;
  line-height: .46rem;
}
.del{
  position: absolute;
  font-size: .15rem;
  color: #4e545d;
  display: inline-block;
  height: .44rem;
  line-height: .44rem;
  top: 0px;
  right: .15rem;
  z-index: 5
}
.cart_page .tags{
  margin-top: .15rem;
}
.quantity{
  display: flex;
  justify-content: flex-start;
  span{
    line-height: .24rem;
    width: .26rem;
    height: .24rem;
    border: 1px solid #c7c7cd;
    cursor: pointer;
    text-align: center;
  }
  input{
    width: .26rem;
    border:none;
    border-bottom: 1px solid #c7c7cd;
    border-top: 1px solid #c7c7cd;
    border-radius: 0px;
    border-image-width: 0px;
    -webkit-box-shadow: 0px;
    box-shadow: 0px;
    vertical-align: bottom;
    text-align: center;
  }
}
.card-goods__item{
    padding: 15px 0;
    border-bottom: 1px solid #e8eaed;
    background: #fff;
}
.head{
      padding-left: 5px;
  // border-bottom: 1px solid #eee;
}
.van-submit-bar{
  bottom: .5rem;
}
.card{
  // background: #f7f7f7;
  .van-submit-bar__bar {
      border-top: 1px solid #e4e2e2;
      .van-checkbox{
        padding-left: 5px;
      }
  }
  .promotion{
      .van-tag {
          line-height: 12px;
          margin-right: 5px;
      }
      .van-cell__title{

      flex: 4;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      }
    }
    .promotion-group{
      position: fixed;
      width: 100%;
      top: .46rem;
      bottom: 1rem;
      overflow-y: auto;
    }
}
.cart_null{
  padding-top: .8rem;
  text-align: center;
  img{
    width: .5rem;
    vertical-align: inherit;
  }
  p{
    font-size: .14rem;
    text-align: center;
  }
  span{
    // display: block;
    background: #F93835 ;
    font-size: .14rem;
    padding: .1rem .35rem;
    border-radius: .06rem;
    color: #fff;
    font-size: .14rem;
  }
}
    
</style>